﻿using System;
using System.Linq;
using Microsoft.SharePoint;

namespace PD.ShP.Code
{
    /// <summary>
    /// Extensions for SPUserCollection member for accessing users safely.
    /// </summary>
    public static class SPUserCollectionHelper
    {
        /// <summary>
        /// Gets the sharepoint user by name safe.
        /// </summary>
        /// <param name="collection">The collection of sharepoint users.</param>
        /// <param name="name">The display name of the user.</param>
        /// <returns>
        /// An user if exists; otherwise null.
        /// </returns>
        public static SPUser GetByNameSafe(this SPUserCollection collection, string name)
        {
            try
            {
                return collection.OfType<SPUser>().FirstOrDefault(x => string.Compare(x.Name, name, StringComparison.OrdinalIgnoreCase) == 0);
            }
            catch (SPException)
            {
                return null;
            }
        }

        /// <summary>
        /// Gets the by login name safe.
        /// </summary>
        /// <param name="collection">The collection.</param>
        /// <param name="loginName">Name of the login.</param>
        /// <returns>
        /// An user if exists; otherwise null.
        /// </returns>
        public static SPUser GetByLoginNameSafe(this SPUserCollection collection, string loginName)
        {
            try
            {
                return collection[loginName];
            }
            catch (SPException)
            {
                return null;
            }
        }

        /// <summary>
        /// Gets the sharepoint user by id safe.
        /// </summary>
        /// <param name="collection">The collection of sharepoint users.</param>
        /// <param name="id">The member ID for the user.</param>
        /// <returns>
        /// An user if exists; otherwise null.
        /// </returns>
        public static SPUser GetByIdSafe(this SPUserCollection collection, int id)
        {
            try
            {
                return collection.GetByID(id);
            }
            catch (SPException)
            {
                return null;
            }
        }
    }
}
